package com.example.codegen.resolver;

import com.example.codegen.mapper.MysqlMapper;
import com.example.codegen.model.Column;
import com.example.codegen.model.Datasource;
import com.example.codegen.model.Table;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MysqlResolver implements BaseResolver {

    @Autowired
    public MysqlResolver() {
    }

    /**
     * datasource示例：
     * driver-class-name: com.mysql.cj.jdbc.Driver
     * url: jdbc:mysql://127.0.0.1:3306/test
     * username: root
     * password: 123456
     */
    @Override
    public SqlSession getSession(Datasource datasource) {
        Configuration configuration = getConfiguration(datasource);
        XMLMapperBuilder mysqlXmlMapperBuilder = new XMLMapperBuilder(this.getClass().getClassLoader().getResourceAsStream("mapper/MysqlMapper.xml"), configuration, "Mysql", configuration.getSqlFragments());
        mysqlXmlMapperBuilder.parse();
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession session = sqlSessionFactory.openSession();
        return session;
    }

    @Override
    public String getVersion(Datasource datasource) {
        SqlSession session = getSession(datasource);
        MysqlMapper mysqlMapper = session.getMapper(MysqlMapper.class);
        String version = mysqlMapper.getVersion();
        session.close();
        return version;
    }

    @Override
    public List<Table> getTables(Datasource datasource) {
        SqlSession session = getSession(datasource);
        MysqlMapper mysqlMapper = session.getMapper(MysqlMapper.class);
        List<Table> tables = mysqlMapper.getTables(datasource.getDatabaseName(), datasource.getSchemaName(), null);
        session.close();
        return tables;
    }

    @Override
    public Table getTable(Datasource datasource, String tableName) {
        SqlSession session = getSession(datasource);
        MysqlMapper mysqlMapper = session.getMapper(MysqlMapper.class);
        List<Table> tables = mysqlMapper.getTables(datasource.getDatabaseName(), datasource.getSchemaName(), tableName);
        session.close();
        return tables.size() == 0 ? null : tables.get(0);
    }

    @Override
    public List<Column> getColumns(Datasource datasource, String tableName) {
        SqlSession session = getSession(datasource);
        MysqlMapper mysqlMapper = session.getMapper(MysqlMapper.class);
        List<Column> columns = mysqlMapper.getColumns(datasource.getDatabaseName(), datasource.getSchemaName(), tableName);
        session.close();
        return columns;
    }
}
